//
//  LoadUntrustHttpsRequest.swift
//  EVOP
//
//  Created by LC_WJH on 2017/8/31.
//  Copyright © 2017年 gmc. All rights reserved.
//


//加载不安全https内容辅助类
import Foundation
public class LoadUntrustHttpsRequest:NSObject,NSURLConnectionDelegate,NSURLConnectionDataDelegate{

    
    
    public typealias UCB = (URLRequest)->Void
    private var mycb:UCB?;
    
    
    public func loadUrl(urlStr:String,cb:UCB?)->Void{
        loadRequest(req:URLRequest.init(url:URL.init(string:urlStr)!),cb:cb);
    }
    
    public func loadRequest(req:URLRequest,cb:UCB?)->Void{
        mycb = cb;
        _request =  req
        _urlConnection  = NSURLConnection.init(request:_request!, delegate: self);
        _urlConnection?.start();
    }
    
    
    var _urlConnection : NSURLConnection?;
    public var _request:URLRequest?;
    
    
    public func connection(_ connection: NSURLConnection, willSendRequestFor challenge: URLAuthenticationChallenge){
        
        if challenge.previousFailureCount == 0 {
            let cred =  URLCredential.init(trust: challenge.protectionSpace.serverTrust!)
            challenge.sender?.use(cred, for: challenge)
        }else{
            challenge.sender?.cancel(challenge);
        }
        
        
    }
    
    public func connection(_ connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: URLProtectionSpace) -> Bool{
        return  protectionSpace.authenticationMethod ==  NSURLAuthenticationMethodServerTrust
    }
    
    public func connection(_ connection: NSURLConnection, didReceive response: URLResponse){
        
        
        mycb?(_request!);
       _urlConnection?.cancel();
    }
    
    

    
}
